package com.yuncheng.spcyApi.flow;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yuncheng.spcyApi.busService.BusService;
import com.yuncheng.spcyApi.busService.FlowJobBlsxService;
import com.yuncheng.spcyApi.busService.InitWjjlService;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.entity.SpcySqsxBasic;
import com.yuncheng.spcyApi.entity.SpcySqsxJob;
import com.yuncheng.spcyApi.mapper.SpcySqsxJobMapper;
import com.yuncheng.spcyApi.service.ISpcySqsxBaiscService;
import com.yuncheng.spcyApi.service.ISpcySqsxBczgjlService;
import com.yuncheng.spcyApi.service.ISpcySqsxBqbzjlService;
import com.yuncheng.spcyApi.service.ISpcySqsxJobService;
import com.yuncheng.spcyApi.utils.GetCurrentUserUtils;
import com.yuncheng.spcyApi.vo.common.Result;
import com.yuncheng.spcyApi.vo.flow.SpcyJobSxVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 企业端-流程提交相关
 * @author hua
 */
@Service
public class SpcyQyFlowService {

    private static final Logger log = LoggerFactory.getLogger(SpcyQyFlowService.class);

    @Resource
    private FlowNodeService flowNodeService;

    @Resource
    private ISpcySqsxBaiscService spcySqsxBaiscService;

    @Resource
    private ISpcySqsxJobService spcySqsxJobService;

    @Resource
    private SpcySqsxJobMapper spcySqsxJobMapper;

    @Resource
    private ISpcySqsxBqbzjlService spcySqsxBqbzjlService;

    @Resource
    private ISpcySqsxBczgjlService spcySqsxBczgjlService;

    @Resource
    @Lazy
    private BusService busService;

    @Resource
    private InitWjjlService initWjjlService;

    @Resource
    @Lazy
    private FlowJobBlsxService flowJobBlsxService;

    /**
     *  企业端-流程提交
     */
    public Result passJobByQy(FlowVo flowVo){
        SpcySqsxJob beanJob = spcySqsxJobService.getById(flowVo.getJobid());
        if (beanJob == null){
            return Result.error("没有相匹配的流程数据！");
        }

        if (beanJob.getFhjmc().equals(SpcyFlowConstant.ZDY_HJMC_BQBZ)){

            List<String> dbrList = spcySqsxJobMapper.selectIdsByFhjmc(beanJob.getFpid(), SpcyFlowConstant.HJMC_CLSC, SpcyFlowConstant.HJMC_CLSCFH);
            if (CollectionUtil.isEmpty(dbrList)) {
                List<SpcySqsxJob> clscList = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                        .eq(SpcySqsxJob::getFpid, beanJob.getFpid())
                        .eq(SpcySqsxJob::getFhjmc, SpcyFlowConstant.HJMC_CLSC)
                        .orderByAsc(SpcySqsxJob::getFfssj));
                if (CollectionUtil.isNotEmpty(clscList)) {

                    flowNodeService.copyNewJob(SpcyConstant.BLZT_DB, beanJob.getFpid(),
                            "", "",
                            "", "",
                            clscList.get(0), GetCurrentUserUtils.getCurrentUser(),
                            "", "");
                }
            }

            /** 更新补齐补正完成状态 */
            spcySqsxBqbzjlService.updateWc(beanJob.getFpid());
            spcySqsxBaiscService.updateSqsxByJsbcxxjcljg(beanJob.getFpid(), new Date());

        }
        else if (beanJob.getFhjmc().equals(SpcyFlowConstant.ZDY_HJMC_ZGCL)){

            /** 更新整改完成状态 */
            spcySqsxBczgjlService.updateWc(beanJob.getFpid());
            spcySqsxBaiscService.updateSqsxByJszgjg(beanJob.getFpid());

        }
        else {

            beanJob.setFblyj(Optional.ofNullable(flowVo.getOpinion()).orElseGet(()->"同意"));
        }

        beanJob.setFblsj(new Date());
        beanJob.setFblzt(SpcyConstant.BLZT_YB);
        beanJob.setFbllx(SpcyConstant.BLLX_ZB);
        beanJob.setFblr(beanJob.getFdbr());
        beanJob.setFblbm(GetCurrentUserUtils.getCurrentUserName());
        spcySqsxJobService.updateById(beanJob);

        return Result.ok();
    }

    /**
     * 新增企业-现场检查-流程待办
     * @param currentJob 当前流程
     * @param sqsxid 申请事项id
     * @param dbrid 待办人id
     * @param dbr 待办人
     */
    @Async(value = "asyncSimpleTask")
    public void addQyXcjcJob(SpcySqsxJob currentJob, String sqsxid, String dbrid, String dbr){
        /** 是否已经存在待办 */
        List<SpcySqsxJob> jobList = spcySqsxJobMapper.selectList(new LambdaQueryWrapper<SpcySqsxJob>()
                .eq(SpcySqsxJob::getFpid, sqsxid)
                .eq(SpcySqsxJob::getFnodeid, SpcyFlowConstant.ZDY_HJMC_XCJC_NODE_ID)
                .eq(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_DB));
        if (CollectionUtil.isNotEmpty(jobList)){
            return;
        }

        /** 创建待办 */
        flowNodeService.copyYbJob(sqsxid,
                SpcyFlowConstant.ZDY_HJMC_XCJC_NODE_ID, SpcyFlowConstant.ZDY_HJMC_XCJC,
                dbrid, dbr, currentJob,
                GetCurrentUserUtils.getCurrentUser(), "", "", "", SpcyConstant.BLZT_DB);
    }

    /**
     * 新增企业-整改材料-流程待办
     * @param currentJob 当前流程
     * @param sqsxid 申请事项id
     * @param dbrid 待办人id
     * @param dbr 待办人
     */
    @Async(value = "asyncSimpleTask")
    public void addQyZgclJob(SpcySqsxJob currentJob, String sqsxid, String dbrid, String dbr, String opinion){
        /** 是否已经存在待办 */
        List<SpcySqsxJob> jobList = spcySqsxJobMapper.selectList(new LambdaQueryWrapper<SpcySqsxJob>()
                .eq(SpcySqsxJob::getFpid, sqsxid)
                .eq(SpcySqsxJob::getFnodeid, SpcyFlowConstant.ZDY_HJMC_ZGCL_NODE_ID)
                .ne(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_YB));
        if (CollectionUtil.isNotEmpty(jobList)){
            return;
        }

        flowNodeService.copyYbJob(sqsxid,
                SpcyFlowConstant.ZDY_HJMC_ZGCL_NODE_ID, SpcyFlowConstant.ZDY_HJMC_ZGCL,
                dbrid, dbr, currentJob,
                GetCurrentUserUtils.getCurrentUser(), "", "", opinion, SpcyConstant.BLZT_DB);
    }

    /**
     * 新增-补齐补正流程待办
     */
    public Result addBqbzJob(SpcySqsxBasic sqsx, String sqsxid, String jobid, String opinion){
        return this.addBqbzJob(sqsx, sqsxid, jobid, null, opinion);
    }

    /**
     * 新增企业-补齐补正-流程待办
     * */
    public Result addBqbzJob(SpcySqsxBasic sqsx, String sqsxid, String jobid, SpcySqsxJob currentJob, String opinion){
        if (StringUtils.isBlank(jobid)){
            return Result.ok();
        }

        String dbrid = SpcyFlowConstant.ZDY_HJMC_BQBZ_NODE_FSRID;
        String dbr = "";
        if (sqsx == null){
            sqsx = spcySqsxBaiscService.selectSqsxById(sqsxid);
            dbrid = sqsx.getFqyid();
        }
        dbr = Optional.ofNullable(sqsx.getFqymc()).orElseGet(()->"企业");

        /** 2024-02-27 注释 */
        /*return flowNodeService.createZdJob(jobid, null, opinion,
                GetCurrentUserUtils.getCurrentUser(), true, "",
                dbrid, dbr,
                SpcyFlowConstant.ZDY_HJMC_BQBZ_NODE_ID, SpcyFlowConstant.ZDY_HJMC_BQBZ,
                "", "");*/

        if (currentJob == null) {
            currentJob = spcySqsxJobService.getById(jobid);
            if (currentJob == null) {
                log.error("流程任务id: {}", jobid);
                return Result.error("没有相匹配的流程数据！");
            }
        }
        String pid = currentJob.getFpid();

       /* Result result = flowNodeService.doJob(jobid, currentJob, opinion, true,"","","");
        if (result.isSuccess()) {*/
        SpcySqsxJob newPreviousJob = flowNodeService.copyYbJob(pid,
                SpcyFlowConstant.ZDY_HJMC_BQBZ_NODE_ID, SpcyFlowConstant.ZDY_HJMC_BQBZ,
                dbrid, dbr,
                currentJob, GetCurrentUserUtils.getCurrentUser(),
                "", "",
                opinion, SpcyConstant.BLZT_DB);

        return Result.ok(newPreviousJob);
        /*}

        return Result.ok(); */
    }

    /**
     * 政务企业-补齐补正完成-创建材料审查待办
     */
    @Async(value = "asyncNormalTask")
    public Result zwBqbzwcCreateClscDb(String sqsxid, SpcySqsxBasic sqsx){

        /** 更新补齐补正完成状态 */
        spcySqsxBqbzjlService.updateWc(sqsxid);
        spcySqsxBaiscService.updateSqsxByJsbcxxjcljg(sqsxid, new Date());

        SpcySqsxJob nowDbJob = null;
        /** 是否已经存在待办 */
        List<SpcySqsxJob> jobDbList = spcySqsxJobMapper.selectList(new LambdaQueryWrapper<SpcySqsxJob>()
                .eq(SpcySqsxJob::getFpid, sqsxid)
                .eq(SpcySqsxJob::getFhjmc, SpcyFlowConstant.HJMC_CLSC)
                .ne(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_YB));
        if (CollectionUtil.isEmpty(jobDbList)){

            /** 审评查验流程-当前待办环节 */
            List<SpcySqsxJob> jobYbList = spcySqsxJobMapper.selectList(new LambdaQueryWrapper<SpcySqsxJob>()
                    .eq(SpcySqsxJob::getFpid, sqsxid)
                    .eq(SpcySqsxJob::getFhjmc, SpcyFlowConstant.HJMC_CLSC)
                    .eq(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_YB)
                    .orderByDesc(SpcySqsxJob::getFfssj));
            if (CollectionUtil.isNotEmpty(jobYbList)){
                nowDbJob = jobYbList.get(0);

                /** 创建待办 */
                flowNodeService.copyNewJob(SpcyConstant.BLZT_DB, sqsxid,
                        "", "",
                        "", "",
                        nowDbJob, null,
                        "", "");
            }

        }else {
            nowDbJob = jobDbList.get(0);
        }

        /** 完成补齐补正 */
        List<SpcyJobSxVo> bzJobList = spcySqsxJobService.selectDbJobSxListByFpid(sqsxid, SpcyFlowConstant.ZDY_HJMC_BQBZ, null);
        if (CollectionUtil.isNotEmpty(bzJobList)) {
            LambdaUpdateWrapper<SpcySqsxJob> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(SpcySqsxJob::getFpid, sqsxid);
            updateWrapper.eq(SpcySqsxJob::getFhjmc, SpcyFlowConstant.ZDY_HJMC_BQBZ);
            updateWrapper.eq(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_DB);

            SpcySqsxJob updateJob = new SpcySqsxJob();
            updateJob.setFblzt(SpcyConstant.BLZT_YB);
            updateJob.setFbllx(SpcyConstant.BLLX_BL);
            updateJob.setFblsj(new Date());
            updateJob.setFblbm(SpcyConstant.QY_ORG_NAME);
            updateJob.setFblr(sqsx.getFqymc());
            try {
                updateJob.setFsyts(flowJobBlsxService.jsTwoDateBetweenDays(bzJobList.get(0).getFksyts(), sqsxid, bzJobList.get(0).getFfssj(), updateJob.getFblsj(), updateJob.getFztkssj(), updateJob.getFztjssj())); // 使用天数
                updateJob.setFsfcs(flowJobBlsxService.isDateBetweenSfcs(updateJob.getFsyts(), bzJobList.get(0).getFcnts())); // 办理是否超时
            } catch (Exception e) {
                log.error("政务企业-补齐补正完成-创建材料审查待办-计算时限错误：{}", e.getMessage());
            }
            spcySqsxJobService.update(updateJob, updateWrapper);
        }

        /** 通知短信 */
        StringBuffer smsContent = new StringBuffer("【补充材料通知】\n");
        if (StringUtils.isNotBlank(sqsx.getFqymc())){
            smsContent.append(sqsx.getFqymc()).append(" ");
        }

        if (StringUtils.isNotBlank(sqsx.getFsxmc())){
            smsContent.append(sqsx.getFsxmc());
        }
        smsContent.append("的补齐补正已经完成了。");
        if (nowDbJob != null) {
            busService.sendNextNodeSmsContent(nowDbJob, smsContent.toString());
        }

        return Result.ok();
    }

    /**
     * 政务企业-整改完成
     */
    @Async(value = "asyncNormalTask")
    public Result zwZgwcCreateNotice(String sqsxid, SpcySqsxBasic sqsx){

        /** 更新整改完成状态 */
        spcySqsxBczgjlService.updateWc(sqsxid);
        spcySqsxBaiscService.updateSqsxByJszgjg(sqsxid);

        /** 通知短信内容 */
        StringBuffer smsContent = new StringBuffer("【整改通知】\n");
        if (StringUtils.isNotBlank(sqsx.getFqymc())){
            smsContent.append(sqsx.getFqymc()).append(" ");
        }

        if (StringUtils.isNotBlank(sqsx.getFsxmc())){
            smsContent.append(sqsx.getFsxmc());
        }
        smsContent.append("的材料整改已经完成了。");

        /** 获取主办人环节 */
        List<SpcySqsxJob> jobYbList = spcySqsxJobMapper.selectList(new LambdaQueryWrapper<SpcySqsxJob>()
                .eq(SpcySqsxJob::getFpid, sqsxid)
                .eq(SpcySqsxJob::getFhjmc, SpcyFlowConstant.HJMC_CLSC)
                .eq(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_YB)
                .orderByAsc(SpcySqsxJob::getFfssj));
        if (CollectionUtil.isNotEmpty(jobYbList)) {
            /** 发送短信 */
            busService.sendNextNodeSmsContent(jobYbList.get(0), smsContent.toString());
        }

        /** 完成整改 */
        /*LambdaUpdateWrapper<SpcySqsxJob> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SpcySqsxJob::getFpid, sqsxid);
        updateWrapper.eq(SpcySqsxJob::getFhjmc, SpcyFlowConstant.ZDY_HJMC_ZGCL);
        updateWrapper.eq(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_DB);

        SpcySqsxJob updateJob = new SpcySqsxJob();
        updateJob.setFblzt(SpcyConstant.BLZT_YB);
        updateJob.setFbllx(SpcyConstant.BLLX_BL);
        updateJob.setFblsj(new Date());
        updateJob.setFblbm(SpcyConstant.QY_ORG_NAME);
        updateJob.setFblr(sqsx.getFqymc());
        spcySqsxJobService.update(updateJob, updateWrapper);*/

        return Result.ok();
    }

    /**
     * 办结-企业现场检查环节
     */
    public void bjQtXcjcJob(String sqsxid, SpcySqsxBasic sqsx){

        /** 完成流程 */
        LambdaUpdateWrapper<SpcySqsxJob> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SpcySqsxJob::getFpid, sqsxid);
        updateWrapper.eq(SpcySqsxJob::getFnodeid, SpcyFlowConstant.ZDY_HJMC_XCJC_NODE_ID);
        updateWrapper.eq(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_DB);

        SpcySqsxJob updateJob = new SpcySqsxJob();
        updateJob.setFblzt(SpcyConstant.BLZT_YB);
        updateJob.setFbllx(SpcyConstant.BLLX_BL);
        updateJob.setFblsj(new Date());
        updateJob.setFblbm(SpcyConstant.QY_ORG_NAME);
        updateJob.setFblr(sqsx.getFqymc());
        updateJob.setFblyj("同意");
        spcySqsxJobService.update(updateJob, updateWrapper);

    }

    /**
     * 新增-经办人阅知提醒-环节
     * @param isSmsFlag 短信标志
     * @param smsContent 短信内容
     */
    @Async(value = "asyncNormalTask")
    public void addJbryztxJob(SpcySqsxBasic sqsx, String sqsxid, SpcySqsxJob copyJob, boolean isSmsFlag, String smsContent){
        if (sqsx == null){
            sqsx = spcySqsxBaiscService.selectSqsxYwxxById(sqsxid);
        }

        /*String flowCode = SpcyFlowConstant.getJbryztxFlowCodeByYwflcode(sqsx.getFywflcode());
        List<SysFlowNode> nodeByCodeJdmc = sysFlowNodeService.getNodeByCodeJdmc(flowCode, SpcyFlowConstant.HJMC_JBRYZTX);
        if (CollectionUtil.isEmpty(nodeByCodeJdmc)){
            log.error(flowCode+">流程结点配置为空！"+SpcyFlowConstant.HJMC_JBRYZTX);
            return;
        }*/

        /** 方案及相关文件自动盖章 */
        try {
            initWjjlService.verifyAutoFileGzByFazd(sqsxid);
        }catch (Exception e){
            log.error("经办人阅知提醒-自动盖章错误：{}", e.getMessage());
        }


        /** 验证是否已经盖章 */
        String errorMsg = initWjjlService.verifyFaspFileIsGz(sqsxid);
        if (StringUtils.isBlank(errorMsg)){
            return;
        }

        List<String> jobList = spcySqsxJobService.selectDbIdByFpidAndFhjmc(sqsxid, SpcyFlowConstant.HJMC_JBRYZTX);
        if (CollectionUtil.isNotEmpty(jobList)){
            return;
        }

        SpcySqsxJob newPreviousJob = flowNodeService.copyZdyNewJob(SpcyConstant.BLZT_DB, sqsxid,
                SpcyFlowConstant.JBRYZTX_001002_FLOW_CODE, SpcyFlowConstant.HJMC_JBRYZTX,
                sqsx.getFzbr(), sqsx.getFjbrmc(),
                copyJob, GetCurrentUserUtils.getCurrentUser(),
                "", "");

        /**
         * 接收返回的流程任务，如果返回的流程任务id不相等，发送短信
         * 发送下环节短信
         */
        if (isSmsFlag){
            busService.sendNextNodeSmsContent(newPreviousJob, smsContent);
        }
    }
}
